package gui;

import java.io.*;
import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Calendar;
import java.util.Scanner;
import java.text.ParseException;

public class Calendar1 extends JFrame implements MouseListener {
	int year, month, day;
	public Hashtable<String, Data> hashtable;
	File file;
	JTextField showDay[];
	JLabel title[];
	Calendar cal;
	int week;
	NotePad notepad = null;
	Month chmonth;
	Year chyear;
	String weekday[] = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
	JPanel leftPanel, rightPanel;

	public Calendar1() {
		setTitle("DoTgt @" + Login.user);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocation(500, 280);
		setResizable(false);
		setSize(850, 400);
		JMenuBar menubar = new JMenuBar();
		JMenu menu1 = new JMenu("Menu");
		leftPanel = new JPanel();
		JPanel leftCenter = new JPanel();
		JPanel leftNorth = new JPanel();
		leftCenter.setLayout(new GridLayout(7, 7));
		rightPanel = new JPanel();
		// this.year = year;
		// this.month = month;
		// this.day = day;
		cal = Calendar.getInstance();
		Date currentDate = cal.getTime();
		year = Integer.parseInt((new SimpleDateFormat("yyyy")
				.format(currentDate)));
		month = Integer.parseInt((new SimpleDateFormat("MM")
				.format(currentDate)));
		day = Integer
				.parseInt((new SimpleDateFormat("dd").format(currentDate)));
		chyear = new Year(this);
		chyear.setYear(year);
		chmonth = new Month(this);
		chmonth.setMonth(month);
		title = new JLabel[7];
		showDay = new JTextField[42];
		JMenuItem mcreate = new JMenuItem("Create");
		JMenuItem mview = new JMenuItem("View");
		menu1.add(mcreate);
		menu1.add(mview);
		menubar.add(menu1);
		setJMenuBar(menubar);

		mcreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				Create create = new Create();
				create.setVisible(true);
				dispose();
			}
		});

		mview.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				View view = new View();
				view.setVisible(true);
			}
		});

		for (int j = 0; j < 7; j++) {
			title[j] = new JLabel();
			title[j].setText(weekday[j]);
			title[j].setBorder(BorderFactory.createRaisedBevelBorder());
			leftCenter.add(title[j]);
		}
		title[0].setForeground(Color.red);
		title[6].setForeground(Color.red);
		for (int i = 0; i < 42; i++) {
			showDay[i] = new JTextField();
			showDay[i].addMouseListener(this);
			showDay[i].setEditable(false);
			leftCenter.add(showDay[i]);
		}

		cal = Calendar.getInstance();
		Box box = Box.createHorizontalBox();
		box.add(chyear);
		box.add(chmonth);
		leftNorth.add(box);
		leftPanel.setLayout(new BorderLayout());
		leftPanel.add(leftNorth, BorderLayout.NORTH);
		leftPanel.add(leftCenter, BorderLayout.CENTER);
		leftPanel.validate();
		Container con = getContentPane();
		JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
				leftPanel, rightPanel);
		split.setDividerLocation(600);
		split.setDividerSize(0);
		con.add(split, BorderLayout.CENTER);
		con.validate();
		readFile();
		notepad = new NotePad(this);
		rightPanel.add(notepad);
		set(year, month);
		setVisible(true);
	}

	public void set(int year, int month) {
		cal.set(year, month - 1, 1);
		week = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (month == 1 || month == 2 || month == 3 || month == 5 || month == 7
				|| month == 8 || month == 10 || month == 12) {
			sort(week, 31);
		} else if (month == 4 || month == 6 || month == 9 || month == 11) {
			sort(week, 30);
		} else if (month == 2) {
			if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
				sort(week, 29);
			} else {
				sort(week, 28);
			}
		}
	}

	public void sort(int weekday, int monthday) {
		for (int i = weekday, n = 1; i < weekday + monthday; i++) {
			showDay[i].setText("" + n);
			if (n == day) {
				showDay[i].setForeground(Color.blue);
				showDay[i].setFont(new Font("TimesRoman", Font.BOLD, 20));
			} else {
				showDay[i].setFont(new Font("TimesRoman", Font.BOLD, 12));
				showDay[i].setForeground(Color.black);
			}
			if (i % 7 == 6) {
				showDay[i].setForeground(Color.red);
			}
			if (i % 7 == 0) {
				showDay[i].setForeground(Color.red);
			}
			n++;
		}
		for (int i = 0; i < weekday; i++) {
			showDay[i].setText("");
		}
		for (int i = weekday + monthday; i < 42; i++) {
			showDay[i].setText("");
		}
	}

	public int getYear() {
		return year;
	}

	public void setYear(int y) {
		year = y;
		notepad.setYear(year);
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int m)

	{
		month = m;
		notepad.setMonth(month);
	}

	public int getDay() {
		return day;
	}

	public void setDay(int d) {
		day = d;
		notepad.setDay(day);
	}

	public Hashtable<String, Data> getHashtable() {
		return hashtable;
	}

	public File getFile() {
		return file;
	}

	public void readFile() {
		File[] files = getList();
		hashtable = new Hashtable<String, Data>();
		for (final File f : files) {
			try {
				Scanner scanFile = new Scanner(f);
				String title = scanFile.nextLine(); // Title
				String date = scanFile.nextLine(); // Date
				String group = scanFile.nextLine(); // Group
				String detail = scanFile.nextLine(); // Detail
				while (scanFile.hasNext())
					detail += "\n" + scanFile.nextLine();
				Data d = new Data(f.getName(), title, date, group, detail);
				if (hashtable.containsKey(date)) {
					int i = 1;
					while (hashtable.containsKey(date + "-" + i))
						i++;
					date = date + "-" + i;
				}
				hashtable.put(date, d);
				scanFile.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	private File[] getList() {
		File dir = new File(Login.data_dir);
		File[] files = dir.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".txt")
						&& name.toLowerCase().startsWith(Login.user + "-");
			}
		});
		return files;
	}

	public void mousePressed(MouseEvent e) {
		JTextField source = (JTextField) e.getSource();
		try {
			day = Integer.parseInt(source.getText());
			notepad.setDay(day);
			notepad.setmessage(year, month, day);
			notepad.settext(null);
			notepad.setcontent(year, month, day);
		} catch (Exception ee) {
		}
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}
}

class NotePad extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;
	JTextArea text;
	JButton save, delete;
	Hashtable<String, Data> table;
	JLabel message;
	int year, month, day;
	File file;
	Calendar1 calendar;
	SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
	JButton prev = new JButton("<");
	JButton next = new JButton(">");
	int page = 1;

	public NotePad(Calendar1 calendar) {
		this.calendar = calendar;
		year = calendar.getYear();
		month = calendar.getMonth();
		day = calendar.getDay();
		table = calendar.getHashtable();
		file = calendar.getFile();
		try {
			message = new JLabel(""
					+ df.format(df.parse(year + "/" + month + "/" + day)),
					JLabel.CENTER);
		} catch (ParseException e) {
		}
		message.setFont(new Font("TimesRoman", Font.BOLD, 16));
		message.setForeground(Color.blue);
		text = new JTextArea(10, 10);
		save = new JButton("save data");
		delete = new JButton("delete data");
		save.addActionListener(this);
		delete.addActionListener(this);
		prev.addActionListener(this);
		next.addActionListener(this);
		prev.setEnabled(false);
		try {
			if (!table.containsKey(df.format(df.parse(year + "/" + month + "/"
					+ day))
					+ "-" + page)) {
				prev.setVisible(false);
				next.setVisible(false);
			} else {
				prev.setVisible(true);
				next.setVisible(true);
			}
		} catch (ParseException e) {
		}
		setLayout(new BorderLayout());
		JPanel pSouth = new JPanel();
		GridBagLayout g = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		c.gridwidth = 1;
		c.gridheight = 1;
		c.gridx = 0;
		c.gridy = 0;
		g.setConstraints(save, c);
		c.gridx = 1;
		c.gridy = 0;
		g.setConstraints(delete, c);
		c.anchor = GridBagConstraints.WEST;
		c.insets = new Insets(20, 0, 0, 0);
		c.gridx = 0;
		c.gridy = 1;
		g.setConstraints(prev, c);
		c.anchor = GridBagConstraints.EAST;
		c.gridx = 1;
		c.gridy = 1;
		g.setConstraints(next, c);
		pSouth.setLayout(g);
		add(message, BorderLayout.NORTH);
		pSouth.add(save);
		pSouth.add(delete);
		pSouth.add(prev);
		pSouth.add(next);
		add(pSouth, BorderLayout.SOUTH);
		add(new JScrollPane(text), BorderLayout.CENTER);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == save) {
			save(year, month, day);
		} else if (e.getSource() == delete) {
			delete(year, month, day);
		} else if (e.getSource() == prev) {
			page--;
			setcontent(year, month, day);
			if (page == 1)
				prev.setEnabled(false);
			if (!next.isEnabled())
				next.setEnabled(true);
		} else if (e.getSource() == next) {
			page++;
			setcontent(year, month, day);
			try {
				if (!table.containsKey(df.format(df.parse(year + "/" + month
						+ "/" + day))
						+ "-" + page))
					next.setEnabled(false);
			} catch (ParseException pe) {
			}
			if (!prev.isEnabled())
				prev.setEnabled(true);
		}
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getYear() {
		return year;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getMonth() {
		return month;
	}

	public void setDay(int day) {
		this.day = day;
	}

	public int getDay() {
		return day;
	}

	public void setmessage(int year, int month, int day) {
		try {
			message.setText(""
					+ df.format(df.parse(year + "/" + month + "/" + day)));
		} catch (ParseException e) {
		}
	}

	public void settext(String s) {
		text.setText(s);
	}

	public void setcontent(int year, int month, int day) {
		try {
			String key = ""
					+ df.format(df.parse(year + "/" + month + "/" + day));
			if (page != 1)
				key += "-" + (page - 1);
			if (table.containsKey(key)) {
				text.setText((String) table.get(key).getDetail());
			} else {
				text.setText("");
			}
		} catch (ParseException e) {
		}
		try {
			if (!table.containsKey(df.format(df.parse(year + "/" + month + "/"
					+ day))
					+ "-1")) {
				prev.setVisible(false);
				next.setVisible(false);
			} else {
				prev.setVisible(true);
				next.setVisible(true);
				if (page == 1)
					prev.setEnabled(false);
				else
					prev.setEnabled(true);
			}
		} catch (ParseException e) {
		}
	}

	public void save(int year, int month, int day) {
		try {
			String eventcon = text.getText();
			String key = df.format(df.parse(year + "/" + month + "/" + day));
			if (page != 1)
				key += "-" + (page - 1);
			String m = df.format(df.parse(year + "/" + month + "/" + day))
					+ "save?";
			int ok = JOptionPane.showConfirmDialog(this, m, "ask ",
					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			if (ok == JOptionPane.YES_OPTION) {
				try {
					Data d;
					DateFormat dateFormat = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					Date date = new Date();
					String filename = Login.user + "-"
							+ dateFormat.format(date);
					if (table.containsKey(key)) {
						d = table.get(key);
						d.setDetail(eventcon);
					} else
						d = new Data(filename, "No Title", key, "No Group",
								eventcon);
					table.put(key, d);
					createTask(d);
				} catch (Exception ee) {
				}
			}
		} catch (ParseException e) {
		}
	}

	public void delete(int year, int month, int day) {
		try {
			String key = df.format(df.parse(year + "/" + month + "/" + day));
			if(page != 1)
				key += "-" + (page-1);
			if (table.containsKey(key)) {
				String m = df.format(df.parse(year + "/" + month + "/" + day))
						+ "delete?";
				int ok = JOptionPane
						.showConfirmDialog(this, m, "ask",
								JOptionPane.YES_NO_OPTION,
								JOptionPane.QUESTION_MESSAGE);
				if (ok == JOptionPane.YES_OPTION) {
					try {
						Data d = table.get(key);
						File f = new File(Login.data_dir + d.getFile() + ".txt");
						f.delete();
						page = 1;
						calendar.readFile();
						table = calendar.getHashtable();
						setcontent(year,month,day);
					} catch (Exception ee) {
					}
				}
			}
			else {
				String m = df.format(df.parse(year + "/" + month + "/" + day))
						+ "none";
				JOptionPane.showMessageDialog(this, m, "warning ",
						JOptionPane.WARNING_MESSAGE);
			}
		} catch (ParseException e) {
		}
	}

	public void createTask(Data d) {
		String filename = d.getFile();
		File create = new File(Login.data_dir + filename + ".txt");
		try {
			create.createNewFile();
		} catch (IOException ioe) {
			System.out.print(ioe);
		}
		try {
			java.io.PrintWriter lpw = new PrintWriter(new FileWriter(create,
					false));
			lpw.write(d.getTitle() + "\r\n");
			lpw.write(d.getDate() + "\r\n");
			lpw.write(d.getGroup() + "\r\n");
			lpw.write(d.getDetail() + "\r\n");
			lpw.close();
		} catch (IOException ioe) {
			System.out.print(ioe);
		}
	}
}

class Year extends Box implements ActionListener

{
	int year;
	JTextField showYear = null;
	JButton NextYear, LastYear;
	Calendar1 cal;

	public Year(Calendar1 cal) {
		super(BoxLayout.X_AXIS);

		showYear = new JTextField(4);
		showYear.setForeground(Color.blue);
		showYear.setFont(new Font("TimesRomn", Font.BOLD, 14));
		this.cal = cal;
		year = cal.getYear();
		NextYear = new JButton("Next");
		LastYear = new JButton("Pervious");
		add(NextYear);
		add(showYear);
		add(LastYear);
		showYear.addActionListener(this);
		LastYear.addActionListener(this);
		NextYear.addActionListener(this);
	}

	public void setYear(int year) {
		this.year = year;
		showYear.setText("" + year);
	}

	public int getYear() {
		return year;
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == LastYear) {
			year = year - 1;
			showYear.setText("" + year);
			cal.setYear(year);
			cal.set(year, cal.getMonth());
		} else if (e.getSource() == NextYear) {
			year = year + 1;
			showYear.setText("" + year);
			cal.setYear(year);
			cal.set(year, cal.getMonth());
		} else if (e.getSource() == showYear) {
			try

			{
				year = Integer.parseInt(showYear.getText());
				showYear.setText("" + year);
				cal.setYear(year);
				cal.set(year, cal.getMonth());
			} catch (NumberFormatException ee) {
				showYear.setText("" + year);
				cal.setYear(year);
				cal.set(year, cal.getMonth());
			}
		}
	}

}

class Month extends Box implements ActionListener

{
	int month;
	JTextField showMonth = null;
	JButton NextMonth, PreviousMonth;

	Calendar1 cal;

	public Month(Calendar1 cal) {
		super(BoxLayout.X_AXIS);
		this.cal = cal;
		showMonth = new JTextField(2);
		month = cal.getMonth();
		showMonth.setEditable(false);
		showMonth.setForeground(Color.blue);
		showMonth.setFont(new Font("TimesRomn", Font.BOLD, 16));
		NextMonth = new JButton("Next Month");
		PreviousMonth = new JButton("Previous Month");
		add(PreviousMonth);
		add(showMonth);
		add(NextMonth);
		PreviousMonth.addActionListener(this);
		NextMonth.addActionListener(this);
		showMonth.setText("" + month);
	}

	public void setMonth(int month) {
		if (month <= 12 && month >= 1) {
			this.month = month;
		} else {
			this.month = 1;
		}
		showMonth.setText("" + month);
	}

	public int getMonth() {
		return month;
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == PreviousMonth) {
			if (month >= 2) {
				month = month - 1;
				cal.setMonth(month);
				cal.set(cal.getYear(), month);
			} else if (month == 1) {
				month = 12;
				cal.setMonth(month);
				cal.set(cal.getYear(), month);
			}
			showMonth.setText("" + month);
		}

		else if (e.getSource() == NextMonth) {
			if (month < 12) {
				month = month + 1;
				cal.setMonth(month);
				cal.set(cal.getYear(), month);
			} else if (month == 12) {
				month = 1;
				cal.setMonth(month);
				cal.set(cal.getYear(), month);
			}
			showMonth.setText("" + month);
		}
	}
}
